﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace XmlDSigEx
{
    class SameDocumentDereferencer:IUriDereferencer
    {
        #region IUriDereferencer Members

        public object DereferenceUri(string uri, XmlDocument context)
        {
            if (uri == string.Empty)
                return context.DocumentElement.SelectNodes("(//. | //@* | //namespace::*)").ConvertToListOf<XmlNode>();
            string id = uri.TrimStart('#');
            XmlElement element = context.GetElementById(id);
            if(element == null)
            element = context.SelectSingleNode(string.Format("//*[@ID='{0}']", id)) as XmlElement;
            if(element == null)
            element = context.SelectSingleNode(string.Format("//*[@id='{0}']", id)) as XmlElement;
            if (element == null)
                element = context.SelectSingleNode(string.Format("//*[@Id='{0}']", id)) as XmlElement;

            if (element == null)
                throw new IDUriNotFoundException(string.Format("The element with id {0} could not be found.", uri));
            return element.SelectNodes("(.//. | .//@* | .//namespace::*)").ConvertToListOf<XmlNode>();
        }

        #endregion
    }
}
